//
//  WorkHomeVC.m
//  XLDoctor
//
//  Created by longma on 2018/7/27.
//  Copyright © 2018年 XLH. All rights reserved.
//mj手机区号

#import "SearchAllCountryCodeVC.h"
#import "CountryCodeCell.h"
#import "MJSearchBarView.h"
#import "UITableView+SCIndexView.h"
#import "CountryCodeModel.h"
#define searchBarView_H 56
@interface SearchAllCountryCodeVC ()<UITableViewDelegate,UITableViewDataSource,UITextFieldDelegate>
@property (nonatomic, strong) MJUITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) NSMutableArray *dataSourceArray;
@property (nonatomic, assign) NSInteger selectIndex;
@property (nonatomic, strong) MJSearchBarView *searchBarView;

@end

@implementation SearchAllCountryCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}

- (void)mj_setUI{
    [super mj_setUI];
    [self.navigationController setNavigationBarHidden:true animated:NO];

    self.view.backgroundColor = UIColor.mj_backgroundColor;
    self.mj_titleLocalizable = @"Choose Region";
    NSMutableArray *dataSourceArray = [HealthHelper getAreaCodesJsonDataSource];

    self.dataSourceArray = [NSMutableArray array];
    [dataSourceArray enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
        CountryCodeModel *model = [[CountryCodeModel alloc]init];
        model.nameEN = obj[@"英文名"];
        model.nameZhHansCN = obj[@"中文名"];
        model.nameZhHantCN = obj[@"港澳繁体"];
        model.nameZhHantTW = obj[@"台湾繁体"];
        model.nameRU = obj[@"俄语"];
        model.nameID = obj[@"印尼语"];

        model.ID = obj[@"id"];
        model.code = obj[@"区号"];
        model.ISO = obj[@"ISO"];
        [self.dataSourceArray addObject:model];
    }];
   
    [self.view addSubview:self.searchBarView];
    [self.searchBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(18);
        make.right.equalTo(self.view).offset(-18);
        make.top.equalTo(self.view).offset(STATUS_BAR_HEIGHT + 10);
        make.height.equalTo(@(searchBarView_H));
    }];
    
    [[self rac_signalForSelector:@selector(textFieldShouldReturn:) fromProtocol:@protocol(UITextFieldDelegate)] subscribeNext:^(RACTuple * _Nullable x) {
        UITextField *tf = (UITextField *)x.first;
         [tf resignFirstResponder];
//         weakSelf.pageNumber = 1;
//         [weakSelf requestData];
//        [weakSelf searchPatient];
        
    }];
    [self.searchBarView.searchTextField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    [self.view addSubview:self.tableView];

    self.selectIndex = -1;
    [self.tableView reloadData];
}

#pragma mark - 方法
#pragma mark - 方法
- (void)textFieldDidChange:(UITextField *)textField{
    NSString *searchStr = self.searchBarView.searchTextField.text.length ? self.searchBarView.searchTextField.text : @"";
    if(searchStr.length){
        //筛选数据
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"nameEN BEGINSWITH[c] %@",searchStr];
        if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
            pred = [NSPredicate predicateWithFormat:@"nameZhHansCN BEGINSWITH[c] %@",searchStr];
        }
        if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
            pred = [NSPredicate predicateWithFormat:@"nameZhHantCN BEGINSWITH[c] %@",searchStr];
        }
        if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
            pred = [NSPredicate predicateWithFormat:@"nameZhHantTW BEGINSWITH[c] %@",searchStr];
        }
        if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
            pred = [NSPredicate predicateWithFormat:@"nameRU BEGINSWITH[c] %@",searchStr];
        }
        if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
            pred = [NSPredicate predicateWithFormat:@"nameID BEGINSWITH[c] %@",searchStr];
        }
        NSArray *filteredArray = [self.dataSourceArray filteredArrayUsingPredicate:pred];
        self.dataArray = [NSMutableArray arrayWithArray:filteredArray];
        
        NSLog(@"MJLog=========searchStr==============%@",searchStr);
        
        [self showEmptyView];
        [self.tableView reloadData];
    }
}
- (void)showEmptyView{
    if(self.dataArray.count > 0){
        [self hideEmptyView:self.tableView];
        self.tableView.mj_footer.hidden = false;
    }else{
        self.tableView.mj_footer.hidden = true;
        [self showEmptyView:self.tableView emptyStyle:EmptyViewCountryCode];
    }
}
- (void)requestData{
    
}

#pragma mark - 代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewAutomaticDimension;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    CountryCodeCell *cell = [CountryCodeCell reuseForTableView:tableView forIndexPath:indexPath];
    CountryCodeModel *model = self.dataArray[indexPath.row];
    NSString *name = @"";
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleEN){
        name = model.nameEN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHansCN){
        name = model.nameZhHansCN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantCN){
        name = model.nameZhHantCN;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleZhHantTW){
        name = model.nameZhHantTW;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleRU){
        name = model.nameRU;
    }
    if(LanguageHelper.shared.mLanguageStyle == MJLanguageStyleID){
        name = model.nameID;
    }
    cell.titleLabel.text = name;
    cell.subTitleLabel.text = [NSString stringWithFormat:@"%@",model.code];
    cell.subTitleLabel.edgeInsets = UIEdgeInsetsMake(10, 10, 10, 10);
    if(self.selectIndex == indexPath.row){
        cell.isSelect = true;
    }else{
        cell.isSelect = false;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
  
    self.selectIndex = indexPath.row;
    [tableView reloadData];
    
    NSMutableArray *dataSourceArray = [HealthHelper getAreaCodesJsonDataSource];
    CountryCodeModel *model = self.dataArray[indexPath.row];
    
    NSDictionary *countryAreaCode = [dataSourceArray mj_filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"id == %@", model.ID]];
    MJWeakSelf
    MJUIAfter_GCD(0.35, ^{
        
        if(weakSelf.handleCountryCodeBlock){
            weakSelf.handleCountryCodeBlock(countryAreaCode);
        }
        [weakSelf.navigationController popViewControllerAnimated:false];
    });
}


#pragma mark - 懒加载
- (NSMutableArray *)dataArray {
    if (_dataArray == nil) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

- (MJUITableView *)tableView{
    if (!_tableView){
//        MJUITableView *tableView = [[MJUITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        MJUITableView *tableView = [[MJUITableView alloc] initWithFrame:CGRectMake(0, STATUS_BAR_HEIGHT + searchBarView_H + 20, self.view.bounds.size.width, self.view.bounds.size.height - STATUS_BAR_HEIGHT - searchBarView_H - 20) style:UITableViewStylePlain];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.backgroundColor = UIColor.mj_backgroundColor;
        tableView.rowHeight = UITableViewAutomaticDimension;
        tableView.estimatedRowHeight = 140;
        tableView.sectionIndexColor = UIColor.mj_appColor;
        [CountryCodeCell registerNibWithTableView:tableView];
        _tableView = tableView;
    }
    return _tableView;
}
- (MJSearchBarView *)searchBarView {
    if (!_searchBarView) {
        MJWeakSelf
        //继承 MJUICustomXibView 的view 用 initWithFrame 初始化（重要）
        _searchBarView = [[MJSearchBarView alloc]initWithFrame:CGRectZero];
        _searchBarView.searchTextField.mj_pLocalizable = @"Enter region name";
        _searchBarView.autoresizingMask = UIViewAutoresizingNone;
        _searchBarView.leftButton.hidden = false;
        [_searchBarView.leftButton mj_addAction:^(UIButton *button) {
            [weakSelf.searchBarView.searchTextField resignFirstResponder];
            [weakSelf mj_popViewController];
        }];
        _searchBarView.searchTextField.returnKeyType = UIReturnKeySearch; //设置按键类型
        _searchBarView.searchTextField.delegate = self;
        [_searchBarView.searchTextField mj_becomeFirstResponder];
    }
    return _searchBarView;
}
@end
